import { createStore } from "@/vuex";
const plugins1 = (store) => {
  store.subscribe((mutation, state) => {
    console.log(mutation, state);
  });
};
const customPlugin = (store) => {
  const local = sessionStorage.getItem("vuexState");
  console.log(local);
  setTimeout(() => {
    if (local) {
      store.replaceState(JSON.parse(local));
    }
  });
  store.subscribe((mutation, state) => {
    sessionStorage.setItem("vuexState", JSON.stringify(state));
  });
};

const store = createStore({
  strict: true, //开启严格模式，只能通过mutation修改状态
  plugins: [plugins1, customPlugin],
  state: {
    count: 0,
  },
  getters: {
    // 计算属性，
    doubleCount(state) {
      return state.count * 2;
    },
  },
  mutations: {
    // 同步操作
    increment(state, payload) {
      state.count += payload;
    },
  },
  actions: {
    //其他的action，或者调用 mutations
    incrementAction({ commit }, payload) {
      return new Promise((resolve, reject) => {
        setTimeout(() => {
          commit("increment", payload);
          resolve("成功");
        }, 1000);
      });
    },
  },
  modules: {
    aCount: {
      name: "aCount",
      namespaced: true,
      state: {
        count: 0,
      },

      mutations: {
        increment(state, payload) {
          state.count += payload;
        },
      },
      actions: {
        //其他的action，或者调用 mutations
        incrementAction({ commit }, payload) {
          return new Promise((resolve, reject) => {
            setTimeout(() => {
              commit("increment", payload);
              resolve("成功");
            }, 1000);
          });
        },
      },
      // modules: {
      //   cCount: {
      //     name: "cCount",
      //     namespaced: true,
      //     state: {
      //       count: 0,
      //     },
      //     mutations: {
      //       increment(state, payload) {
      //         state.count += payload;
      //       },
      //     },
      //   },
      // },
    },
    bCount: {
      name: "bCount",
      namespaced: true,
      state: {
        count: 0,
      },
      mutations: {
        increment(state, payload) {
          state.count += payload;
        },
      },
    },
  },
});
store.registerModule(["aCount", "cCount"], {
  name: "cCount",
  namespaced: true,
  state: {
    count: 0,
  },
  mutations: {
    increment(state, payload) {
      state.count += payload;
    },
  },
});
export default store;
